/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.rpc;

import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.AbstractUpgradeModulePackageRpcServiceImpl;
import com.je.common.base.service.rpc.UpgradeModulePackageRpcService;
import com.je.common.base.upgrade.PackageResult;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.workflow.service.model.ModelService;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;

@RpcSchema(schemaId = "upgradeModulePackageRpcService")
public class UpgradeModulePackageRpcServiceImpl extends AbstractUpgradeModulePackageRpcServiceImpl implements UpgradeModulePackageRpcService {

    @Autowired
    private MetaService metaService;

    @Autowired
    private ModelService modelService;

    private final Logger logger = LoggerFactory.getLogger(UpgradeModulePackageRpcServiceImpl.class);

    @Override
    public PackageResult packageModule(DynaBean upgradeBean) {
        PackageResult packageResult = new PackageResult();
        List<String> workflowIdList = upgradeBean.get("workflowIdList") == null ? new ArrayList<>() : (List<String>) upgradeBean.get("workflowIdList");
        packageResult.setProductWorkflows(packageWorkflow(workflowIdList));
        return packageResult;
    }

    @Override
    @Transactional
    public String installModule(PackageResult packageResult) {
        List<DynaBean> workflows = packageResult.getProductWorkflows();
        if(workflows!=null){
            for(DynaBean workflow:workflows){
                workflow.table("JE_WORKFLOW_PROCESSINFO");
                String processinfoId =workflow.getStr("JE_WORKFLOW_PROCESSINFO_ID");
                DynaBean workflowDb = metaService.selectOne("JE_WORKFLOW_PROCESSINFO",ConditionsWrapper.builder().eq("JE_WORKFLOW_PROCESSINFO_ID",processinfoId));
                if(workflowDb==null){
                    workflow.setStr("JE_WORKFLOW_PROCESSINFO_ID",processinfoId);
                    commonService.buildModelCreateInfo(workflow);
                    metaService.insert(workflow);
                    String modelId= modelService.doSave(workflow, workflow.getStr("metaInfoJson"), workflow.getStr("metaInfoXml"));
                    workflow.table("JE_WORKFLOW_PROCESSINFO");
                    workflow.setStr("PROCESSINFO_MODEL_ID",modelId);
                    metaService.update(workflow,ConditionsWrapper.builder().eq("JE_WORKFLOW_PROCESSINFO_ID",processinfoId));
                }else{
                    String modelId = workflow.getStr("PROCESSINFO_MODEL_ID");
                    String xmlId = workflow.getStr("PROCESSINFO_RESOURCE_XML_ID");
                    modelService.doUpdate(modelId,xmlId,workflow,workflow.getStr("metaInfoJson"),workflow.getStr("metaInfoXml"));
                }
                modelService.deploy(processinfoId);
            }
        }
        return null;
    }

    private List<DynaBean> packageWorkflow(List<String> workflowIds) {
        List<DynaBean> workflowBeanList = metaService.select("JE_WORKFLOW_PROCESSINFO", ConditionsWrapper.builder()
                .in("JE_WORKFLOW_PROCESSINFO_ID",workflowIds));
        for(DynaBean dynaBean :workflowBeanList){
           String xmlId = dynaBean.getStr("PROCESSINFO_RESOURCE_XML_ID");
           String modelId = dynaBean.getStr("PROCESSINFO_MODEL_ID");
           dynaBean.set("metaInfoXml",modelService.getXmlInfoById(xmlId));
           dynaBean.set("metaInfoJson",modelService.getJsonInfoById(modelId));
        }
        return workflowBeanList;
    }

    @Override
    public String doCheck(PackageResult packageResult) {
        return null;
    }
}
